﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using l1cs.server.model;
using MySql.Data.MySqlClient;
using System.Data;
using l1cs.server.utils;

namespace l1cs.server.datatables
{
    /// <summary>
    /// 血盟クラス（一応Wrapper形式に直したが、どうもアルゴリズムが理解できない。）
    /// </summary>
    public class BuddyTable
    {
        private static Logger _log = Logger.getLogger( typeof( BuddyTable ).FullName );

        private static BuddyTable _instance;

        private Dictionary<int, L1Buddy> _buddys = new Dictionary<int, L1Buddy>();

        public static BuddyTable getInstance()
        {
            if ( _instance == null )
            {
                _instance = new BuddyTable();
            }
            return _instance;
        }

        private BuddyTable()
        {
            String sqlstr = "SELECT distinct(char_id) as char_id FROM character_buddys";
            using ( MySqlWrapper wrapper = new MySqlWrapper() )
            {
                foreach ( DataRow item in wrapper.GetDataTable( sqlstr ).Rows )
                {
                    int charId = SqlUtils.toInt( item["char_id"] );
                    sqlstr = "SELECT buddy_id, buddy_name FROM character_buddys WHERE char_id = ?1";
                    MySqlCommand cmd = new MySqlCommand( sqlstr );
                    cmd.Parameters.Add( "?1", MySqlDbType.Int32 ).Value = charId;
                    DataTable dt2 = wrapper.GetDataTable( cmd );
                    L1Buddy buddy = new L1Buddy( charId );
                    foreach ( DataRow item2 in dt2.Rows )
                    {
                        // TODO 優先度5 そもそも複数血盟に加入はないはずでは・・・
                        int buddy_id = SqlUtils.toInt( item2["buddy_id"] );
                        String buddy_name = Convert.ToString( item2["buddy_name"] );
                        buddy.add( buddy_id, buddy_name );
                    }
                    _buddys[buddy.getCharId()] = buddy;
                }
            }
            _log.config( "loaded " + _buddys.Count + " character's buddylists" );
        }

        /// <summary>
        /// プレイヤーIDから所属する血盟情報を取得する。
        /// </summary>
        /// <param name="charId">プレイヤーID</param>
        /// <returns>血盟情報</returns>
        public L1Buddy getBuddyTable( int charId )
        {
            L1Buddy buddy;
            _buddys.TryGetValue( charId, out buddy );
            if ( buddy == null )
            {
                buddy = new L1Buddy( charId );
                _buddys[charId] = buddy;
            }
            return buddy;
        }

        /// <summary>
        /// プレイヤーIDと血盟IDを結びつけてDBに保存する。(血盟加入)
        /// </summary>
        /// <param name="charId">プレイヤーID</param>
        /// <param name="objId">血盟ID</param>
        /// <param name="name">血盟名</param>
        public void addBuddy( int charId, int objId, String name )
        {
            String sqlstr = @"INSERT INTO character_buddys SET 
                            char_id    = ?1, 
                            buddy_id   = ?2, 
                            buddy_name = ?3";
            using ( MySqlWrapper wrapper = new MySqlWrapper() )
            {
                MySqlCommand cmd = new MySqlCommand( sqlstr );
                cmd.Parameters.Add( "?1", MySqlDbType.Int32 ).Value = charId;
                cmd.Parameters.Add( "?2", MySqlDbType.Int32 ).Value = objId;
                cmd.Parameters.Add( "?3", MySqlDbType.String ).Value = name;
                cmd.ExecuteNonQuery();
            }
        }

        /// <summary>
        /// プレイヤーIDで血盟情報を削除する。(血盟脱退)
        /// </summary>
        /// <param name="charId">プレイヤーID</param>
        /// <param name="buddyName">血盟名</param>
        public void removeBuddy( int charId, String buddyName )
        {
            L1Buddy buddy = getBuddyTable( charId );
            if ( !buddy.containsName( buddyName ) )
            {
                return;
            }

            String sqlstr = @"DELETE FROM character_buddys WHERE 
                            char_id    = ?1 AND 
                            buddy_name = ?2";
            using ( MySqlWrapper wrapper = new MySqlWrapper() )
            {
                MySqlCommand cmd = new MySqlCommand( sqlstr );
                cmd.Parameters.Add( "?1", MySqlDbType.Int32 ).Value = charId;
                cmd.Parameters.Add( "?2", MySqlDbType.String ).Value = buddyName;
                cmd.ExecuteNonQuery();
            }
            buddy.remove( buddyName );
        }
    }
}
